package cn.myschool.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author oldliu
 * @since 1.0
 */
public class MybatisUtil {
    private MybatisUtil() {
    }

    private static SqlSessionFactory sessionFactory;

    static {
        InputStream in = null;
        try {
            in = Resources.getResourceAsStream("mybatis-config.xml");
            sessionFactory = new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession get() {
        return sessionFactory.openSession();
    }

    public static SqlSession get(boolean autoCommit) {
        return sessionFactory.openSession(autoCommit);
    }

    public static void close(SqlSession s) {
        if (s != null) {
            s.commit();
            s.close();
        }
    }
}
